import React, { useState ,useEffect} from "react";
import { Modal,Divider,Alert,Button,Form,Select,message} from 'antd';
import classNames from "classnames";
import axios from 'axios'
import {editVideoStatus,setRemark} from 'api/index'
import LlxForm from 'components/LlxForm/index'
  // 将时间转化为秒
  const ToSeconds = (t) => {
    var s = 0.0
    if (t) {
      var p = t.split(':')
      for (let i = 0; i < p.length; i++) {
        s = s * 60 + parseFloat(p[i].replace(',', '.'))
      }
    }
    return s * 1000
  }
 const getText = (textItem) => {
    let value = ''
    textItem.forEach((i, index) => {
      if (index > 1 && index < textItem.length) {
        value = value + i
      }
    })
    return value
  }
      // 获取字幕内容，发送一个get请求
    const  GetSrtInfo = (srtUrl,setSrtData) => {
        var reg = /[-�〝\]\[\)\(\{\}［］＂〞´ˋ〈〉「」『』︵︷︿︹︽﹁﹃︻ˆ？！﹍﹎_＿﹏﹌￣ˉ﹊﹉¡¿ˇ︼﹄﹂︾︺﹀︸︶]/g
        axios
          .get(`${srtUrl}`)
          .then(function(response) {
              console.log(response);

              response.data=response.text

            let a = null
            if (response.data.indexOf('\n\r\n') !== -1) {
              a = response.data.split(/\n\r\n/)
            } else {
              a = response.data.split(/\n\n/)
            }
            for (let i = 0; i < a.length; i++) {
              if (a[i].indexOf('\n') === 0) {
                a[i] = a[i].slice(1)
                if (a[i].indexOf('\n') === 0) {
                  a[i] = a[i].slice(1)
                }
              }
            }
            const textList = a
              .filter(item => item !== '')
              .map((item, index) => {
                const textItem = item.split(/\n/)
                return {
                  show: false,
                  showBefore: false,
                  index: index,
                  sort: textItem[0],
                  value: getText(textItem).replace(reg, ''),
                  bg: ToSeconds(textItem[1].split(' --> ')[0]),
                  ed: ToSeconds(textItem[1].split(' --> ')[1]),
                  timeLine: textItem[1]
                }
              })
              setSrtData(textList)
          })
      }

      const ExamineVideo = (props) => {

        const {isModalVisible, setIsModalVisible,dictionaries,examineData} = props
      
        const [form] = Form.useForm()
        if(!isModalVisible) return <div></div>
      
        const manager = examineData.videoStatus==='Q'||examineData.videoStatus==='PQ'?dictionaries.QandPQ:dictionaries.UserSpecies
        
        const item = ['Q','PQ'].includes(examineData.videoStatus)?[
          {label: '备注内容',type:'textArea', name: 'remark' , span: 24 }
      ]:[
          {label: '负责人', name: 'manager' , span: 24 ,rules:[
            {
              required: true,
              message: '请选择负责人'
            },
          ],render:()=>{
            return  <Select
            allowClear
            optionFilterProp="dictValue"
            showSearch
            fieldNames={{value:'userName',label:'userName'}}
            placeholder={'请选择负责人'}
            options={manager}
          >
          </Select>
          }},
          {label: '备注内容',type:'textArea', name: 'remark' , span: 24 }
      ]
      // 返回
           const  getNewStatus = (value) => {
            switch (value) {
              case 'N':
                return 'R'
              case 'PN':
                return 'PR'
              case 'R':
                return 'Q'
              case 'Q':
                return 'P'
              case 'PR':
                return 'PQ'
              case 'PQ':
                return 'P'
                default:
                  return
            }
          }
        const handleOk = () => {
          form.validateFields().then(async()=>{
            await editVideoStatus({
              id: examineData.id,
              videoStatus:getNewStatus(examineData.videoStatus),
              qmanager: ['R', 'PR','N','PN'].includes(examineData.videoStatus) ? form.getFieldValue().manager : '',
              rmanager: ''
            })
            // 留言
            await setRemark({
              manager: form.getFieldValue().manager,
              dataId: examineData.id,
              type: 'VIDEO',
              remark: form.getFieldValue().remark,
              statusNow: examineData.videoStatus,
              statusNext:getNewStatus(examineData.videoStatus)
            })
      
            message.success('审核通过')
      
            setIsModalVisible(false)
      
          })
        }
      
        const handleCancel = () => {
          setIsModalVisible(false)
        }
      
        return   <Modal destroyOnClose width={950} title="审核视频" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <LlxForm form={form} labelCol={5} formItem={item} />
      </Modal>
      }

const PreviewAudio = (props) => {
  const {isModalVisible, setIsModalVisible,prevewVideo,examineData,dictionaries,getNewList,userName} = props

  const [time,setTime] = useState(0)
  const [srtData,setSrtData] = useState([])
  const [isModalVisibleExamineVideo,setIsModalVisibleExamineVideo] = useState(false)


  useEffect(()=>{
     if(!isModalVisible) return
    if(prevewVideo.videoUrl&&prevewVideo.srtUrl){
       GetSrtInfo(prevewVideo.srtUrl,setSrtData)
    }

    return ()=>{
       setTime(0)
       setSrtData([])
    }
 },[isModalVisible])// eslint-disable-line react-hooks/exhaustive-deps
  // 返回
  const handleOk = async () => {
    setIsModalVisible(false);
    getNewList()
  }
  const onCancel = () => {
    setIsModalVisible(false);
  };
  // 播放中
  const onTimeUpdate = (e) => {
    setTime(e.target.currentTime*1000)
  }
  const isAdopt = () => {
    if(examineData.videoStatus==='P') return message.error('该数据已发布')
    if(['N','PN'].includes(examineData.videoStatus)&&userName!==examineData.createBy) return  message.error('你不是创建人')
    if(['Q','R','PQ','PR'].includes(examineData.videoStatus)&&(userName!==examineData.qmanager||userName!==examineData.rmanager)) return  message.error('你不是负责人')

    setIsModalVisibleExamineVideo(true)
  }
  
  return   <Modal wrapClassName="modal-full" destroyOnClose  visible={isModalVisible} onOk={handleOk} onCancel={onCancel}>
      <div className="full-modal-title">
          <Alert message={'视频预览'} type="success" />
      </div>

      {
        props.showBtn?<div style={{float:'right'}}>
        <Button onClick={isAdopt} size="mini" type={'primary'}>通过审核</Button>
      </div>:''
      }

      <div  className="preview-video" >
        <video src={prevewVideo?.videoUrl} controls  onTimeUpdate={onTimeUpdate}></video>


        <div className="video-show">
         <Divider>字幕预览</Divider>
         <ul>
          {
            srtData.map((i,j)=>{
              return <li key={j} className={classNames(i.bg<time&&i.ed>time?'text-srt-active':'')}>
                {i.value}
              </li>
            })
          }
        </ul>
        </div>
      </div>
       {/* 快速审核弹框 */}
     <ExamineVideo dictionaries={dictionaries} examineData={examineData} isModalVisible={isModalVisibleExamineVideo} setIsModalVisible={setIsModalVisibleExamineVideo}></ExamineVideo>
   </Modal>

}
export default PreviewAudio